import axios from 'axios';

/** 存储缓存数据 */
const cacheMap = new Map<string, {state: 'pending' | 'complete'; data: any; callbackList: RequestCallback[]}>();

export const request = (request: any, cacheKey: string) => {
  // 判断是否需要缓存
  if (cacheKey) {
    const cacheMapData = cacheMap.get(cacheKey);
    if (cacheMapData) {
      // 判断当前的接口缓存状态，如果是 complete ，则代表缓存完成
      if (cacheMapData.state === 'complete') {
        return Promise.resolve(cacheMap.get(cacheKey)?.data);
      }

      // 如果是 pending ，则代表正在请求中，这里放入回调函数
      if (cacheMapData.state === 'pending') {
        return new Promise((resolve, reject) => {
          cacheMapData.callbackList.push({onSuccess: resolve, onError: reject});
        });
      }
    }

    cacheMap.set(cacheKey, {state: 'pending', data: null, callbackList: []});
  }

  return axios(request)
    .then(res => {
      const cacheMapData = cacheMap.get(cacheKey);
      // 触发回调
      if (cacheMapData) {
        cacheMapData.callbackList.forEach(callback => callback.onSuccess(res));
      }
      cacheMap.set(cacheKey, {state: 'complete', data: res, callbackList: []});
      return res;
    })
    .catch(error => {
      const cacheMapData = cacheMap.get(cacheKey);
      if (cacheMapData) {
        cacheMapData.callbackList.forEach(callback => callback.onError(error));
        cacheMap.delete(cacheKey);
      }
      return error;
    });
};

// 定义一下回调的格式
interface RequestCallback {
  onSuccess: (data: any) => void;
  onError: (error: any) => void;
}
